#include "main.h"
#include "uart.h"
#include <string.h>

extern UART_HandleTypeDef huart2;
extern DMA_HandleTypeDef hdma_usart2_rx;



uint8_t rx_buff[RX_BUFF_LEN];
uint8_t rxout_buff[RX_BUFF_LEN];
uint16_t rx_len;
uint8_t rx_flag = 0;
int uart_init(void)
{
	rx_flag = 0;
	rx_len = 0;
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart2, rx_buff, RX_BUFF_LEN);
	return 0;
}

int uart_handle(void)
{

	HAL_UART_DMAStop(&huart2);
	if (__HAL_UART_GET_IT_SOURCE(&huart2, UART_IT_IDLE)) {
		__HAL_UART_CLEAR_IDLEFLAG(&huart2);
	}
	rx_len = RX_BUFF_LEN - __HAL_DMA_GET_COUNTER(&hdma_usart2_rx);
	rx_flag = 1;
	memcpy(rxout_buff, rx_buff, rx_len);
	HAL_UART_Receive_DMA(&huart2, rx_buff, RX_BUFF_LEN);
	return 0;
}

int uart_send(uint8_t *buff, uint16_t len)
{
	HAL_UART_Transmit(&huart2, buff, len, 100);
	return 0;
}

int uart_recv(uint8_t *buff, uint16_t *len)
{
	if (rx_flag == 1) {
		memcpy(buff, rxout_buff, rx_len);
		*len = rx_len;
		rx_flag = 0;
		return 0;
	}
	return -1;
}
